import useUserStore from "@/store/modules/user";
import axios from "axios";
import { ElMessage,ElLoading,ElNotification } from "element-plus";
import { Base64 } from "js-base64";
//加载效果
const loading = {
    loadingInstance:null,//实例对象
    open(){
        if(this.loadingInstance == null){
            this.loadingInstance = ElLoading.service({
                text:"拼命加载中...",
                background:"rgba(0,0,0,0.5)",
                target:".main"
            }) as any;
        }
    },
    close(){
        if(this.loadingInstance != null){
            this.loadingInstance.close();
        }
        this.loadingInstance = null;
    }
}
const request = axios.create({
    // baseURL: "/mock",
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000,
    //headers: {'X-Custom-Header': 'foobar'}
});
//token加密
function basicToken() {
    const token = localStorage.getItem("B0445-token");
    const base64 = Base64.encode(token + ":");
    return "Basic " + base64;
}
//对比用户权限是否被更改，更改则退出页面
const getMenus = () => {
    const userStore = useUserStore();
    const roleId = userStore.user?.role_id;
    //如果是超级管理员就不用判断
    if (userStore.user?.username == "admin") return;
    request.post("/menus", { roleId }).then((res) => {
        if (res.status == 0) {
            const menus = res.data.menus;
            const userMenus = userStore.user?.role?.menus as string[]
            if (userMenus?.length == menus.length && JSON.stringify([...menus].sort()) == JSON.stringify([...userMenus].sort())){
                return
            }else{
                userStore.removeStoreUser()
                ElMessage({
                    type:"warning",
                    message:"当前用户权限异常，请重新登录"
                })
                window.location.href = "/login"
                
            }
        }else{
            
        }

    })
}

// 请求拦截器
request.interceptors.request.use(
    function (config) {
        //如果本地有token再添加
        
        const token = localStorage.getItem("B0445-token");
        if (token) {
            config.headers.authorization = basicToken();
        }
        if(config.url != "/menus" && config.url != "/login"){
            loading.open();
            getMenus()
        }
        // Do something before request is sent
        return config;
    },
    function (error) {
        loading.close()
        // Do something with request error
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    function (response) {
        const resp = response.data
        if(resp.status != 0){
            ElNotification({
                title:"警告!",
                message:resp.msg,
                type:"warning"
            })
        }
        loading.close()
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response.data;
    },
    function (error) {
        loading.close()
        let msg = "";
        // 获取http状态码
        let status = error.response.status;
        switch (status) {
            case 401:
                msg = "token过期";
                break;
            case 403:
                msg = "无权访问";
                break;
            case 404:
                msg = "请求地址错误";
                break;
            case 500:
                msg = "服务器错误";
                break;

            default:
                msg = "无网络";
                break;
        }
        ElMessage({
            message: msg,
            type: "error",
        });
        return Promise.reject(error);
    }
);

//   对外暴露
export default request;
